<template>
  <div
    class="article"
    v-html="htmlStr"
  />
</template>

<script>
import { getArticleById } from '@/api/article/article'
export default {
  data() {
    return {
      htmlStr: ''
    }
  },
  mounted() {
    this.load()
  },
  methods: {
    async load() {
      const id = this.$route.query.id
      const data = await getArticleById(id)
      const article = data.data
      this.htmlStr = article.content || ''
      const titleHtml = `<h1 style='text-align: center;'><span style='font-size: 24px;'><strong>${article.title}</strong></span></h1><p><br></p><p style='text-align: center;''> <span style='color: rgb(140, 140, 140); font-size: 14px;'>发布时间：${article.startTime} &nbsp;文章来源：${article.source} </span>
    <span style='color: rgb(140, 140, 140); font-size: 14px;'><br>`
      this.htmlStr = titleHtml + this.htmlStr
      this.htmlStr = this.tagAddStyle(this.htmlStr, 'img', 'max-width:100%;height:auto;display: block;margin:0 auto;')
      this.htmlStr = this.tagAddStyle(
        this.htmlStr,
        'div data-w-e-type="video" data-w-e-is-void',
        'text-align:center;'
      )
      this.htmlStr = this.tagAddStyle(this.htmlStr, 'video', 'width:100%;height:auto;')
    },
    // 给标签添加样式
    tagAddStyle(htmlstr, tag, style) {
      // 正则匹配所有img标签
      const regex1 = new RegExp('(i?)(<' + tag + ")(?!(.*?style=['\"](.*)['\"])[^>]+>)", 'gmi')
      // 给不含style="" 或 style='' 的img标签加上style=""
      htmlstr = htmlstr.replace(regex1, '$2 style=""$3')
      // 正则匹配含有style的img标签
      // eslint-disable-next-line prefer-regex-literals
      const regex2 = new RegExp('(i?)(<' + tag + ".*?style=['\"])([^>]+>)", 'gmi')
      // 在img标签的style里面增加css样式(这里增加的样式：display:block;max-width:100%;height:auto;border:5px solid red;)
      htmlstr = htmlstr.replace(regex2, `$2${style}$3`)
      return htmlstr
    }
  }
}
</script>

<style lang="scss" scoped>
.article{
  width: 1000px;
}
</style>
